import http from '../components/common/tui-request';
import appConfig from '@/appConfig.js';
// import store from '../store'
import { encryptMI, decryptMI } from './jsencryptUtils.js';
import md5 from 'js-md5';

const getRemoteUrl = async () => {
  let time = new Date().getTime();
  let [error, resp] = await uni.request({
    url: 'http://ryjvrkal3.bkt.clouddn.com/u1.json?v=' + time,
  });
  console.log(resp.data);
  let lines = resp.data;
  return lines;
};
uni.$on('changeBaseUrl', (url) => {
  http.create({
    host: url + '/api',
    // concise: true,
  });
});

//初始化请求配置项
http.create({
  host: appConfig.baseUrl,
  // concise: true,
  // header: {
  // 	'content-type': 'application/x-www-form-urlencoded'
  // }
});
//请求拦截
http.interceptors.request.use(async (config) => {
  console.log('Query', config.data);
  let target = config.url;
  let time = new Date().getTime();
  // config.url = md5(target+'?v='+time)
  // 每次请求 都带入token  在登录的时候 记录下token
  let token = uni.getStorageSync('token');
  if (!config.header) {
    config.header = {};
  }
  config.header[appConfig.tokenName] = token;
  // config.header['TARGET'] = target
  // config.header['UTOKEN'] = encryptMI(target)
  try {
    if (uni.getStorageSync('parentUserId')) {
      config.header['parentUserId'] = uni.getStorageSync('parentUserId');
    }
  } catch (e) {
    //TODO handle the exception
  }
  // uni.clearStorage()

  // // #ifdef APP-PLUS
  // let localHost = uni.getStorageSync('baseUrl')
  // if(config.url.indexOf('http')==-1&&!localHost){
  // 	let base = await getRemoteUrl()
  // 	console.log(base)
  // 	uni.$emit('changeBaseUrl', base[0].url)
  // }
  // // #endif

  if (config.isForm) {
    config.header['content-type'] = 'application/x-www-form-urlencoded';
  }

  if (JSON.stringify(config.data) != '{}') {
    // 并且判断
    let str = JSON.stringify(config.data);
    if (str) {
      if (config.data.jiami !== 1) {
        config.data = {
          query: encryptMI(str),
        };
      }
    } else {
      config.data = {
        query: encryptMI(str),
      };
    }
    // console.log('query',config)
  }
  // console.time('请求耗时')
  return config;
});
//响应拦截
http.interceptors.response.use((resp) => {
  // console.timeEnd('请求耗时')

  console.log(resp);
  if (!resp) {
    return null;
  }

  const response = resp.data;
  //在使用过程中访问不通 调登录页切换节点
  if (
    resp.statusCode == 404 ||
    resp.statusCode == 500 ||
    resp.statusCode == 403 ||
    resp.statusCode == 502 ||
    resp.statusCode == 400
  ) {
    uni.showModal({
      content: '当前网络或线路不可用,请退出更换线路:' + resp.statusCode,
      showCancel: false,
      success: () => {
        // uni.setStorageSync('token', null)
        let account = uni.getStorageSync('account');
        let password = uni.getStorageSync('password');
        let ssss = uni.getStorageSync('ssss');
        uni.clearStorageSync();
        // uni.removeStorageSync('token');
        uni.setStorageSync('account', account);
        uni.setStorageSync('password', password);
        uni.setStorageSync('ssss', ssss);
        uni.reLaunch({
          url: appConfig.loginSetting.loginPath,
        });
      },
    });
  }
  // console.log(appConfig.loginSetting.loginPath)
  try {
    if (typeof response.data == 'string' && response.data.length > 40) {
      // console.time('解密耗时')
      response.data = JSON.parse(decryptMI(response.data));
      // console.timeEnd('解密耗时')
    }
  } catch (e) {
    //TODO handle the exception
  }

  if (response.code == 500 || response.status == 500) {
    if (response.message == '') {
      response.message = '系统开小差了,请稍后重试';
    }
  }
  if (response.code == 400 || response.status == 400) {
    if (response.message == '') {
      response.message = '参数错误，请检查重试';
    }
  }

  // if(store.state.jumpLogined){
  // 	return Promise.reject(response);
  // }

  //TODO
  // console.log(response);
  // console.log(response.code)
  // console.log(response.status)
  if (response.code == appConfig.loginCode) {
    // #ifdef H5
    // store.commit('SetJumpLogined', true)
    // #endif
    if (appConfig.loginSetting.loginModal) {
      uni.removeStorageSync('token');
      // store.commit('user/setUser', null)
      // store.commit('user/showLogin', true)
    } else {
      // 判断是否是首次 首次
      if (uni.getStorageSync('account') && uni.getStorageSync('password')) {
        uni.showModal({
          content: '当前登录过期,请重新登录:' + response.code,
          showCancel: false,
          success: () => {
            let account = uni.getStorageSync('account');
            let password = uni.getStorageSync('password');
            let ssss = uni.getStorageSync('ssss');
            uni.clearStorageSync();
            // uni.removeStorageSync('token');
            uni.setStorageSync('account', account);
            uni.setStorageSync('password', password);
            uni.setStorageSync('ssss', ssss);
            uni.reLaunch({
              url: appConfig.loginSetting.loginPath,
            });
          },
        });
      }
    }
    return Promise.reject(response);
  }

  return response;
});
export default http;
